﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;


namespace MidApp
{   
    /// <summary>
    ///trida pracujici s uzivatelem.
    /// </summary>
    public class ManageUser
    {
        /// <summary>
        ///Metoda porovnava zadane udaje s udaji v DB.
        /// </summary>
        public static bool CompareInputToLogin(string Nick, string Password)
        {
            try
            {
                var user = MidApp.ManageUser.GetUserByNick(Nick);

                if (MidApp.Hasher.PasswordHasher(Password) == user.Password.Trim())
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
            catch (Exception)
            {
                return false;
            }
        }
        /// <summary>
        ///Metoda provede registraci noveho uzivatele.
        /// </summary>
        public static void CreateNewUser(AppLib.User NewUser, string PassToHash)
        {

            NewUser.Password = Hasher.PasswordHasher(PassToHash);
            NewUser.UserID = GetNumberOfUsers() + 1;//primarni klic je celkovy pocet uzivatelu v db zvyseny o 1, muzeme si to dovolit, protoze uzivatele z db nemazeme!!!!

            var dbConn = MidApp.LinqUse.DBConn;
            dbConn.Users.InsertOnSubmit(NewUser);
            dbConn.SubmitChanges();
        }
        /// <summary>
        ///Metoda provede zmenu hesla uzivatele.
        /// </summary>
        public static void AssignNewPasswordToUser(AppLib.User ActualUser, string NewPassword)
        {
            var db = MidApp.LinqUse.DBConn;

            var newUser = (from User in db.Users where User.Nick == ActualUser.Nick select User).First();
            newUser.Password = MidApp.Hasher.PasswordHasher(NewPassword);
            db.SubmitChanges();

        }
        /// <summary>
        ///Metoda aktualizuje udaje o uzivateli v DB.
        /// </summary>
        public static void AssignNewPersonalInfo(AppLib.User UpdatedUser)
        {
            var db = MidApp.LinqUse.DBConn;
            var oldUser = (from User in db.Users where User.UserID == UpdatedUser.UserID select User).First();

            oldUser.Name = UpdatedUser.Name;
            oldUser.Surname = UpdatedUser.Surname;
            oldUser.Address = UpdatedUser.Address;
            oldUser.PhoneNumber = UpdatedUser.PhoneNumber;
            oldUser.PrimaryEmail = UpdatedUser.PrimaryEmail;
            oldUser.SecondaryEmail = UpdatedUser.SecondaryEmail;
            oldUser.ICQNumber = UpdatedUser.ICQNumber;
            oldUser.Password = UpdatedUser.Password;
            oldUser.ImageURL = UpdatedUser.ImageURL;

            db.SubmitChanges();
            
        }
        /// <summary>
        ///Metoda vraci informace o uzivateli se zadanou prezdivkou.
        /// </summary>
        public static AppLib.User GetUserByNick(string Nick)
        {
            var db = MidApp.LinqUse.DBConn;

            return (from User in db.Users where User.Nick == Nick select User).First();
        }
        /// <summary>
        ///Metoda vraci informace o uzivateli podle zadaneho ID.
        /// </summary>
        public static AppLib.User GetUserByID(int ID)
        {
            var db = MidApp.LinqUse.DBConn;

            return (from User in db.Users where User.UserID == ID select User).First();
        }

        //tak tahle metoda je totalni kravina!co kdyz maji dva uzivatele stejna hesla?
        //public static AppLib.User GetUserByPass(string Pass)
        //{
        //    var db = MidApp.LinqUse.DBConn;

        //    return (from User in db.Users where User.Password == Pass select User).First();
        //}

        /// <summary>
        ///Metoda vraci informace o uzivateli se zadanym emailem.
        /// </summary>
        public static AppLib.User GetUserByPrimaryEmail(string Email)
        {
            var db = MidApp.LinqUse.DBConn;

            return (from User in db.Users where User.PrimaryEmail == Email select User).First();
        }
        /// <summary>
        ///Metoda zjistuje, zda uzivatel jiz v DB existuje.
        ///</summary>
        public static bool UserAlreadyExists(string Nick)
        {
            var db = MidApp.LinqUse.DBConn;
            var files = (from User in db.Users where User.Nick == Nick select User).ToList();
            bool b = true;
            if (files.Count > 0)
                b = true;
            else
                b = false;

            return b;

        }
        /// <summary>
        ///Metoda zjistuje, zda zadany email se nachazi v DB.
        /// </summary>
        public static bool DatabaseContainsEmail(string Email)
        {
            var db = MidApp.LinqUse.DBConn;
            bool b = true;

            try
            {
                var file = (from User in db.Users where User.PrimaryEmail == Email select User).First();
                b = true;
            }
            catch (Exception)
            {
                try
                {
                    var file = (from User in db.Users where User.SecondaryEmail == Email select User).First();
                    b = true;
                }
                catch
                {
                    b = false;
                }
            }
            return b;
        }
        /// <summary>
        ///Metoda vraci pocet uzivatelu v databazi.
        ///</summary>
        public static int GetNumberOfUsers()
        {
            var db = MidApp.LinqUse.DBConn;

            return (from User in db.Users select User).Count();
        }
        /// <summary>
        /// Metoda vraci link na avatar obrazek.
        /// <summary>
        public static string GetUserImage(int userID)
        {
            var db = MidApp.LinqUse.DBConn;

            var user = (from User in db.Users where User.UserID == userID select User).First();

            return user.ImageURL;
        }
        /// <summary>
        /// Metoda vygeneruje uzivateli nove heslo, priradi jej, odesle mail o zmene.
        /// <summary>
        public static void ChangePassword(AppLib.User user)
        {
            //vytvoreni noveho hesla
            char[] symbols = {
                                 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j',
                                 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't',
                                 'u', 'v', 'w', 'x', 'y', 'z',
                                 '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'
                             };

            Random random = new Random();
            var newPass = "";
            for (int i = 0; i < 8; i++)
            {
                newPass += symbols[random.Next(symbols.Length)];
            }

            //zmena hesla v databazi
            MidApp.ManageUser.AssignNewPasswordToUser(user, newPass);

            //odeslani mailu s novym heslem
            var message = "Dobrý den,\nVaše heslo bylo změněno.\nPro přihlášení použijte toto heslo: __";
            message += newPass;
            message += "__\n(Znaky __ nejsou součástí hesla.)";

            MidApp.Mailer.Send(user.PrimaryEmail, "Nové heslo", message);
        }
        /// <summary>
        /// Metoda vraci emaily zacinajici prefixem.
        /// <summary>
        public static string[] GetAllUsersEmailsStartingWithPrefix(List<AppLib.User> users, string prefixText)
        { 
            List<string> userEmails = new List<string>();
            foreach (var user in users)
            {
                userEmails.Add(user.PrimaryEmail);                
            }
            userEmails = userEmails.Distinct().ToList();

            List<string> pom = new List<string>(userEmails);
            foreach (var email in pom)
            {
                if (!email.ToLower().StartsWith(prefixText.ToLower()))
                {
                    userEmails.Remove(email);
                }
            }
            return userEmails.ToArray();
        }
        /// <summary>
        /// Metoda vraci vsechny aktivni uzivatele.
        /// <summary>
        public static List<AppLib.User> GetAllActiveUsers()
        {
            var db = MidApp.LinqUse.DBConn;

            return (from User in db.Users where User.Active == true select User).ToList();
        }
    }
}
